<template>
  <a-config-provider :locale="zhCN">
    <!-- 搜索管理 -->
    <a-space direction="vertical" :size="16">
      <a-form layout="inline" :model="searchParams" @finish="doSearch">
        <a-form-item label="空间名称" name="spaceName">
          <a-input
            v-model:value="searchParams.spaceName"
            placeholder="请输入空间名称"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="用户账号" name="userId">
          <a-input
            v-model:value="searchParams.userId"
            placeholder="请输入用户账号"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="空间级别" name="spaceLevel">
          <a-select
            v-model:value="searchParams.spaceLevel"
            placeholder="请选择空间级别"
            :options="SPACE_LEVEL_OPTIONS"
            style="min-width: 180px"
            allow-clear
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">搜索</a-button>
        </a-form-item>
      </a-form>
    </a-space>
    <a-space style="margin-left: 20px">
      <!-- 操作按钮 -->
      <a-button type="primary" href="/edit_space" target="_blank">+ 创建空间</a-button>
      <a-button type="primary" ghost href="/space_analyze?queryPublic=1" target="_blank">分析公共图库</a-button>
      <a-button type="primary" ghost href="/space_analyze?queryAll=1" target="_blank">分析全空间</a-button>
    </a-space>

    <!-- 分界符 -->
    <a-divider />

    <!-- 用户管理 -->
    <a-spin :spinning="loading">
      <a-table
        :columns="columns"
        :data-source="dataList"
        :pagination="pagination"
        @change="doTableChange"
        row-class-name="custom-row"
        class="custom-table"
        bordered
      >
        <template #bodyCell="{ column, record }">
          <!-- 空间级别 -->
          <template v-if="column.dataIndex === 'spaceLevel'">
            <a-tag :color="getTagColor(record.spaceLevel)">
              {{ SPACE_LEVEL_MAP[record.spaceLevel] }}
            </a-tag>
          </template>
          <!-- 使用情况 -->
          <template v-if="column.dataIndex === 'spaceUseInfo'">
            <div>大小：{{ formatSize(record.totalSize) }} / {{ formatSize(record.maxSize) }}</div>
            <div>数量：{{ record.totalCount }} / {{ record.maxCount }}</div>
          </template>
          <template v-else-if="column.dataIndex === 'createTime'">
            {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
          <template v-else-if="column.dataIndex === 'editTime'">
            {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space wrap>
              <a-button type="link" :href="`/edit_space?id=${record.id}`" target="_blank">
                编辑
              </a-button>
              <a-button type="link" danger @click="confirmDelete(record.id)">删除</a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-spin>
  </a-config-provider>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import {
  deleteSpaceByIdUsingDelete,
  getSpaceListVoUsingPost,
} from '@/apis/SpaceInterface.ts'
import { message, Modal } from 'ant-design-vue'
import dayjs from 'dayjs'
import zhCN from 'ant-design-vue/es/locale/zh_CN'
import { SPACE_LEVEL_MAP, SPACE_LEVEL_OPTIONS } from '@/constants/space.ts'
import { formatSize } from '@/utils'

// 行头
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '用户 ID',
    dataIndex: 'userId',
    width: 80,
  },
  {
    title: '空间名称',
    dataIndex: 'spaceName',
  },
  {
    title: '空间级别',
    dataIndex: 'spaceLevel',
  },
  {
    title: '使用情况',
    dataIndex: 'spaceUseInfo',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 数据
const dataList = ref<API.SpaceVO[]>([])
const total = ref(0)
const loading = ref(false)

// 搜索条件
const searchParams = reactive<API.SpaceQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'descend',
})

// 分页参数
const pagination = computed(() => ({
  current: searchParams.current ?? 1,
  pageSize: searchParams.pageSize ?? 10,
  total: total.value,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条`,
}))

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getSpaceListVoUsingPost({
      ...searchParams,
    })
    if (res.data.data) {
      dataList.value = res.data.data.records ?? []
      total.value = res.data.data.total ?? 0
    } else {
      message.error('获取数据失败，' + res.data.message)
    }
  } catch (error) {
    message.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时请求一次
onMounted(() => {
  fetchData()
})

// 搜索
const doSearch = () => {
  searchParams.current = 1
  fetchData()
}

// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 弹窗确认删除
const confirmDelete = (id: number) => {
  Modal.confirm({
    title: '确认删除',
    content: '删除后数据无法恢复，是否继续？',
    okText: '确认',
    cancelText: '取消',
    onOk: () => onDelete(id),
  })
}

// 删除
const onDelete = async (id: number) => {
  if (!id) return
  try {
    const res = await deleteSpaceByIdUsingDelete({ spaceId: id })
    if (res.data.code === 0) {
      message.success('删除成功')
      fetchData()
    } else {
      message.error('删除失败：' + res.data.message)
    }
  } catch (error) {
    message.error('删除失败')
  }
}

// 获取标签颜色
const getTagColor = (level: number) => {
  switch (level) {
    case 0:
      return 'green'
    case 1:
      return 'orange'
    case 2:
      return 'red'
    default:
      return 'blue'
  }
}
</script>

<style scoped>
  /* 使用原生 CSS */
.custom-table {
  .ant-table-tbody > tr > td {
    border-bottom: 1px dashed #d9d9d9;
  }

  .ant-table-thead > tr > th {
    text-align: center;
    background-color: #fafafa;
    font-weight: bold;
    border-bottom: 1px solid #d9d9d9;
  }

  .custom-row {
    text-align: center;
  }

  .custom-row:hover {
    background-color: #f5f5f5; /* 鼠标悬停效果 */
  }
}
</style>
